package com.a01_2021.thousandstimes.general.controller;


import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.general.entity.Experience;
import com.a01_2021.thousandstimes.general.jwt.JwtTokenUtil;
import com.a01_2021.thousandstimes.general.service.ExperienceService;
import com.a01_2021.thousandstimes.utils.AjaxResponse;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author FRQ
 * @since 2021-02-22
 */
@RestController
@RequestMapping("/experience")
public class ExperienceController {

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Resource
    ExperienceService experienceService;

    /**
     * 用于添加用户经历
     *
     * @param experience 经历实体类
     * @return AjaxResponse
     */
    @PreAuthorize("hasAuthority('experience-add')")
    @DS("#header.instanceid")
    @PostMapping("add")
    public AjaxResponse add(Experience experience) throws CustomException {
        Experience returnItem = experienceService.add(experience);
        return AjaxResponse.success(returnItem);
    }

    /**
     * 获取用户自己的经历
     *
     * @param token jwt令牌
     * @return AjaxResponse
     */
    @PreAuthorize("hasAuthority('experience-get')")
    @DS("#header.instanceid")
    @PostMapping("get")
    public AjaxResponse get(@RequestHeader("${jwt.header}") String token) {
        long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        List<Experience> experienceList = experienceService.get(userId);
        return AjaxResponse.success(experienceList);
    }

    /**
     * 获取指定用户的经历
     *
     * @param userId 用户id
     * @return AjaxResponse
     * @throws CustomException 当用户不存在时抛出该异常
     */
    @PreAuthorize("hasAuthority('experience-getFromUserId')")
    @DS("#header.instanceid")
    @PostMapping("getFromUserId")
    public AjaxResponse getFromUserId(long userId) throws CustomException {
        List<Experience> experienceList = experienceService.getFromUserId(userId);
        return AjaxResponse.success(experienceList);
    }
}
